import { UserService } from 'src/app/@core/services/user/user.service';
import { Component, HostListener, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core';
import { DValidateRules } from 'ng-devui';
import { FormLayout } from 'ng-devui';
import { I18nService } from 'ng-devui/i18n';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { AuthService } from 'src/app/@core/services/auth.service';
import { PersonalizeService } from 'src/app/@core/services/personalize.service';
import { LANGUAGES } from 'src/config/language-config';
import { ThemeType } from '../../models/theme';
import { MenuService } from 'src/app/@core/services/menu/menu.service';
@Component({
  selector: 'da-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  private destroy$ = new Subject<void>();
  horizontalLayout: FormLayout = FormLayout.Horizontal;
  tabActiveId: string | number = 'tab1';
  showPassword = false;
  auto :boolean=true
  tabItems: any;
  language: string;
  i18nValues: any;
  toastMessage: any;
  languages = LANGUAGES;
  msgs: Array<Object> = [];
  formData = {
    accountNumber: '',
    password: '',
  };
  formRules: { [key: string]: DValidateRules } = {
    usernameRules: {
      validators: [
        { required: true ,message:'请输入账号'},
        { minlength: 1 },
        { maxlength: 20 },
      ],
    },
    passwordRules: {
      validators: [{ required: true  ,message:'请输入密码'}, { minlength: 6 }, { maxlength: 15 }, { pattern: /^[a-zA-Z0-9\d@$!%*?&.]+(\s+[a-zA-Z0-9]+)*$/ }],
      message: 'Enter a password that contains 6 to 15 digits and letters.',
    },
  };
  @HostListener('window:keydown.enter')
  onEnter() {
    this.onClick();
  }
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private UserService : UserService,
    private translate: TranslateService,
    private i18n: I18nService,
    private menuService :MenuService,
  ) {
    this.language = this.translate.currentLang;
  }
  ngOnInit(): void {
    this.translate
      .get('loginPage')
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.i18nValues = this.translate.instant('loginPage');
      });
    this.translate.onLangChange.pipe(takeUntil(this.destroy$)).subscribe((event: TranslationChangeEvent) => {
      this.i18nValues = this.translate.instant('loginPage');
    });//切换语言
    // this.personalizeService.setRefTheme(ThemeType.Default);//设置默认主题
    this.route.queryParams.pipe(map((param) => param.code)).subscribe((code) => {
      if (code && code.length > 0) {
        setTimeout(() => {
          this.toastMessage = [
            {
              severity: 'success',
              content: this.i18nValues['callbackMessage'],
            },
          ];
        });
      }
    });//oauth认证回调
  }
  onClick() {
    this.UserService.Login(this.formData).subscribe(
      (res: any) => {
        if (this.auto) {
          localStorage.setItem('userinfo', JSON.stringify(res));
          this.UserService.GetUserByEmployeeCode(res.employeeCode).subscribe((data: any) => {
            localStorage.setItem('id', JSON.stringify(data.id));
          });
        } else {
          sessionStorage.setItem('userinfo', JSON.stringify(res));
        }

        // 获取角色ID数组
        const roleIds = res.roles.map((role: { roleId: number }) => role.roleId);

        // 获取菜单项并导航到第一个有效链接
        this.menuService.GetMenusByRole(roleIds).subscribe((data: any) => {
          this.menuService.setMenuItems(data);
          const firstValidLink = this.getFirstValidLink(data);
          if (firstValidLink) {
            this.router.navigate([firstValidLink]);
          }
          if(data.length==0){
            this.showToast('error', '登录失败', '该用户没有页面访问权限');
          }
        });
      },
      (error) => {
        this.showToast('error', '登录失败', '用户名或密码错误');
      }
    );
  }

  private getFirstValidLink(menuItems: any[]): string | null {
    for (const item of menuItems) {
      if (item.link) {
        return item.link;
      }
      if (item.childrenMenu && item.childrenMenu.length > 0) {
        const childLink = this.getFirstValidLink(item.childrenMenu);
        if (childLink) {
          return childLink;
        }
      }
    }
    return null;
  }
  onLanguageClick(language: string) {
    this.language = language;
    localStorage.setItem('lang', this.language);
    this.i18n.toggleLang(this.language);
    this.translate.use(this.language);
  }
  onKeyUp(e: KeyboardEvent) {
    if (e.keyCode === 13) {
      this.onClick();
    }
  }//回车事件
  changeToggle($event: any) {
    this.auto = $event;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框

}
